﻿using DaXiangAudio;
using ET.CommonLibrary;
using ET.DBCommon.DAL;
using ET.DBCommon.Enum;
using ET.DBCommon.Model;
using ET.Score.Service;
using ET.HeartBeat.SharedLibrary;
using ET.Score.Service.Interfaces;
using ET.Score.SharedLibrary.Wcf;
using ET_DbCommon.Model;
using Newtonsoft.Json;
using OfflineSpeechRecognitionMode;
using RadioStationPOC.Views;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Media;
using System.Net;
using System.Net.Sockets;
using System.Speech.Synthesis;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Timers;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using VoicePhone.Common;
using VoicePhone.Utils;

namespace RadioStationPOC
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public Exam_TestQuestion_Task_StepModel CurStep = new Exam_TestQuestion_Task_StepModel();
        public Exam_TestQuestion_Task_StepModel WaitStep = new Exam_TestQuestion_Task_StepModel();
        public Exam_TestQuestion_Task_StepModel TempStep = new Exam_TestQuestion_Task_StepModel();//Add by lukun

        //初始化试卷的调度--Add by zzg
        private List<SequenceDiagramModel> DispatchList = new List<SequenceDiagramModel>();
        //初始化试卷的无线列调--Add by zzg
        private List<SequenceDiagramModel> WirelessList = new List<SequenceDiagramModel>();
        //初始化语音库--Add by lukun
        private List<VoiceLibraryModel> VoiceLibraryList = new List<VoiceLibraryModel>();
        //无线列调语音库
        private List<VoiceLibraryModel> RSVoiceLibraryList = new List<VoiceLibraryModel>();
        //匹配语音库中回复内容，如果不为空则播报。
        private string REPLAY_CONTENT = string.Empty;
        #region 培训模式下操作提示窗体 Add by zzg
       OperationTips MyOperation = null;
        #endregion
        private SystemType m_CurSystemType= SystemType.ATS;
        public SystemType CurSystemType
        {
            get { return this.m_CurSystemType; }
            set
            {
                this.m_CurSystemType = value;
            }
        }
        public string  VirtualTime = DateTime.Now.ToString();
        public DateTime OperVirtualTime { get; set; }
        public UserInfoModel CurUser;
        public static MainWindow CurMainWindow;
        public Audio AudioIdentify;
        public bool Ringing;
        public List<string> ReciveIdentify { get; set; } = new List<string>();
        /// <summary>
        /// 语音用于动态语音库
        /// </summary>
        public List<string> DynamicReception { get; set; } = new List<string>();
        public byte[] CurAudioBuff;
        Timer timer = new Timer(1000);
        Timer timerSpeak = new Timer(500);
        private SolidColorBrush DefaultBrush;
        private SolidColorBrush SwitchBrush = new SolidColorBrush(Color.FromRgb(107, 190, 22));
        #region 新版语音识别
        /// <summary>
        /// 实例化离线语音类
        /// </summary>
        OfflineSpeechRecognitionClass offlineSpeechRecognitionclass = new OfflineSpeechRecognitionClass();
        #endregion

        #region 自由考核模式测试 Add by lukun
        private Socket _udpRecivesock;
        private Socket _udpSendSocket;
        IPEndPoint targetIpEndPoint; //发送ip端口
        EndPoint point;
        //语音识别关键词
        List<VoiceKeyWord> voiceKeyWords = null;
        Dictionary<int, string> voiceDic = new Dictionary<int, string>();//保存播报内容
        #endregion

        HeartBeatInvoker<IHeartBeatService> MyHeartBeatInvoker;
        HeartBeatCallBack server = null;
        IAccountManageService client = null;
        AccountServiceCallBack callbackInstance = null;

        public MainWindow()
        {
            InitializeComponent();
            offlineSpeechRecognitionclass.StopOfflineSpeechClient();//防止程序多开
            offlineSpeechRecognitionclass.StartListener();//用来监听识别软件发来的信息
            string ipAdress = ConfigurationManager.AppSettings["HeartBeatService"];
            string UserName = ConfigurationManager.AppSettings["UserName"];
            server = new HeartBeatCallBack();
            server.MessageReceived += Server_MessageReceived;
            MyHeartBeatInvoker = HeartBeatInit.HeartBeatInitService(server, ipAdress, UserName);

            string EndPoint = ConfigurationManager.AppSettings["AccountService"];
            callbackInstance = new AccountServiceCallBack();
            callbackInstance.MessageReceived += CallbackObject_MessageReceived;
            client = WCFHelper.CreateDuplexClient<IAccountManageService, AccountServiceCallBack>(EndPoint, callbackInstance);
            if (client != null)
            {
                AccountServiceProvider.Get_Instance().helper = client;
            }
            login.ShowDialog();
            if (Login.LoginStatus)
            {
                login.Hide();
            }

        }
        Login login = new Login();
        private void Server_MessageReceived(object sender, GeneralEventArgs<ET.Score.Service.ArgumentBase<string>> e)
        {
            if (e != null)
            {
                if (e.Argument.LoginStatus)
                {
                    var ExamInfo = e.Argument.Model;//登录信息
                    if (!string.IsNullOrWhiteSpace(ExamInfo))
                    {
                        var userLogin = ExamInfo.Split(',').ToList();
                        Login.userId = userLogin[0];
                        Login.username = userLogin[1];
                        Login.examId = int.Parse(userLogin[2]);
                        Login.postId = userLogin[3];
                        Login.LoginStatus=true;
                       
                    }
                    MyHeartBeatInvoker.CheckLogin = false;
                }
            }
        }
        public string ReplyContent;
        private void CallbackObject_MessageReceived(object sender, GeneralEventArgs<ET.Score.Service.ArgumentExam> e)
        {
            if (e != null)
            {
                if (e.Argument != null)
                {
                    if (e.Argument.Id == CurStep.Id)
                    {
                        this.Dispatcher.BeginInvoke(new Action(() =>
                        {
                            TextToSpeak(e.Argument.ReplyContent, VoiceGender.Male);
                        }));
                    }
                }
                var a = e.Argument;
            }
        }
        /// <summary>
        /// 窗体关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            server.MessageReceived -= Server_MessageReceived;
            MyHeartBeatInvoker.Stop();
            this.timer.Stop();
            this.timerSpeak.Stop();
            if (AudioIdentify != null)
                AudioIdentify.Exit();
        }
        /// <summary>
        /// 加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            //离线语音
            offlineSpeechRecognitionclass.getNotifyMessage += GetMyNotifyMessage;
            offlineSpeechRecognitionclass.StartOfflineSpeechClient();//开启指定的客户端程序
            var _WirelessTrainUC = new WirelessTrainUC();
            this.LayoutPOC.Children.Add(_WirelessTrainUC);
            _WirelessTrainUC.RouteHander += this.TetraClick_Event;
            _WirelessTrainUC.WaitHandle += this.EndWaitInjectError;//选手发现问题后则停止后台汇报等待线程
            //this.SendControl.Margin = new Thickness(this.LayOut.ActualWidth / 2 - this.SendControl.ActualWidth, (this.LayOut.ActualHeight - this.SendControl.ActualHeight) / 2 - 60, 0, 0);
            this.AudioControl.Margin = new Thickness(this.LayOut.ActualWidth / 2 - this.AudioControl.ActualWidth, (this.LayOut.ActualHeight - this.AudioControl.ActualHeight) / 2 + 60, 0, 0);
            this.AudioControl.ThumbClick += AudioControl_ThumbClick;
            CurMainWindow = this;
       
            this.timer.Elapsed += Timer_Elapsed;
            this.timer.Start();
            this.timerSpeak.Elapsed += TimerSpeak_Elapsed;
            this.timerSpeak.Start();

            #region 自由考核模式初始化 Add by lukun
            IPAddress ReciveIP = IPAddress.Parse(ConfigurationManager.AppSettings["ReciveIP"].ToString());//接收消息的IP地址
            string RecivePort = ConfigurationManager.AppSettings["RecivePort"].ToString();//接收消息的端口

            IPAddress SendIP = IPAddress.Parse(ConfigurationManager.AppSettings["SendIP"].ToString());//发送方的IP地址
            string SendPort = ConfigurationManager.AppSettings["SendPort"].ToString();//接收消息的端口

            IPEndPoint Reciveip = new IPEndPoint(ReciveIP, Convert.ToInt32(RecivePort));//网络终结点的IP地址和端口号
            _udpRecivesock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            _udpRecivesock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);//端口复用
            _udpRecivesock.Bind(Reciveip);

            IPEndPoint ip = new IPEndPoint(IPAddress.Any, 0);
            _udpSendSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            _udpSendSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);//端口复用
            _udpSendSocket.Bind(ip);

            targetIpEndPoint = new IPEndPoint(SendIP, Convert.ToInt32(SendPort));//绑定发送ip端口
            point = new IPEndPoint(IPAddress.Any, 0);//用来保存发送方的ip和端口号

            Task.Run(new Action(() => { FreeExamModel(); }));//执行自由考核培训模式
            #endregion
            #region 获取自由模式下的操作步骤识别关键词
            var voiceKeyWordConfig = ShareInfo.voiceKeyWordConfig;
            voiceKeyWords = voiceKeyWordConfig.VoiceKeyWords;
            #endregion

            WindowState = WindowState.Maximized;
          
        }

        //识别语音
        public string NofiyMessage = string.Empty;
        /// <summary>
        /// 通知识别语音
        /// </summary>
        /// <param name="MyMessage"></param>
        private void GetMyNotifyMessage(string MyMessage)
        {
            NofiyMessage = MyMessage;
            this.SendCommand();
            if (MyMessage != string.Empty)
                OfflineSpeech.Instance().SetTextBoxValue(MyMessage);
        }
        /// <summary>
        /// 获取虚拟时间
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TimerSpeak_Elapsed(object sender, ElapsedEventArgs e)
        {
            //获取虚拟时间
            this.VirtualTime = AccountServiceProvider.Get_Instance().GetVirtualTime(Login.examId);
            if (string.IsNullOrEmpty(this.VirtualTime))
                return;
            this.Dispatcher.BeginInvoke(new Action(() => { this.labTime.Text = VirtualTime; }));
            //var sayText = "";// AccountServiceProvider.Get_Instance().GetSayText();
            //if (sayText == null)
            //    return;
            //if (sayText.Contains("请重复")) //&& REPLAY_CONTENT != string.Empty)
            //{
            //    MatchKeyWords();
            //    if (REPLAY_CONTENT != String.Empty)
            //    {
            //        sayText = REPLAY_CONTENT;
            //    }
            //    REPLAY_CONTENT = string.Empty;
            //}
            //if (!string.IsNullOrWhiteSpace(sayText))
            //{
            //    this.TextToSpeak(sayText, VoiceGender.Female);
            //}
        }

        /// <summary>
        /// 退出窗体
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void WindowClose_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
            Environment.Exit(-1);
        }
        /// <summary>
        /// 窗体状态
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Label_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            this.WindowState = this.WindowState == WindowState.Maximized ? WindowState.Normal : WindowState.Maximized;
        }

        /// <summary>
        /// 移动窗体
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DockPanel_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            this.DragMove();
        }

        SpeechSynthesizer speech = new SpeechSynthesizer() { Rate = -1 };
        private static object SpeakLock = new object();
        private bool IsSpeaking { get; set; }
        /// <summary>
        /// 播报语音内容
        /// </summary>
        /// <param name="text"></param>
        /// <param name="voiceGender">播报内容的语音性别。无线电台：男声  调度电话：女声。</param>
        public void TextToSpeak(string text, VoiceGender voiceGender)
        {
            Task.Run(new Action(() =>
            {
                lock (SpeakLock)
                {
                    this.IsSpeaking = true;
                    speech.SelectVoiceByHints(voiceGender);
                    speech.Speak(TextSpeakHelper.TextExChange(text));
                    this.IsSpeaking = false;
                }
            }));
        }
        /// <summary>
        /// 设置当前是调度电话还是无线电台
        /// </summary>
        public void SendCommand()
        {
            this.Dispatcher.BeginInvoke(new Action(() =>
            {
                if (CurSystemType == SystemType.ATS)
                    (this.LayoutPOC.Children[0] as WirelessTrainUC).SendCommand(string.Join("", ReciveIdentify));
            }));
        }
     
        /// <summary>
        /// 播放响铃和声音
        /// </summary>
        /// <param name="stepItemEnum"></param>
        public void PlayerSound(StepItemEnum stepItemEnum)
        {
            SoundPlayer player = new SoundPlayer();
            player.SoundLocation = stepItemEnum == StepItemEnum.无线电台_接听 ? "响铃.wav" : "响铃Phone.wav";
            if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + player.SoundLocation))
            {
                player.Load();
                player.PlayLooping();
                Ringing = true;
                int playTime = 0;
                Task.Run(new Action(() =>
                {
                    while (Ringing)
                    {
                        System.Threading.Thread.Sleep(200);
                        playTime += 200;
                        if (playTime >= 5200) break;
                    }
                    player.Stop();
                }));
            }
        }
        /// <summary>
        /// 呼叫等待
        /// </summary>
        /// <returns></returns>
        public bool CallInWaiting()
        {
            bool ringAndTalk = false;
            this.Dispatcher.Invoke(new Action(() =>
            {
                if (WaitStep.OperateId == (int)StepItemEnum.无线电台_接听)
                    ringAndTalk = (this.LayoutPOC.Children[0] as WirelessTrainUC).CallInWaiting(WaitStep);
            }));
            return ringAndTalk;
        }
        /// <summary>
        /// 试卷处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            if (!this.IsSpeaking) return;
            //获取考试步骤
            var result = AccountServiceProvider.Get_Instance().GetCurrentStep(Login.examId);
            if (!string.IsNullOrWhiteSpace(result))
            {
                Exam_TestQuestion_Task_StepModel currentStep = JsonConvert.DeserializeObject<Exam_TestQuestion_Task_StepModel>(result);

                this.Dispatcher.BeginInvoke(new Action(() =>
                {
                    var phone = (this.LayoutPOC.Children[0] as WirelessTrainUC).TrainList.ToList();
                    MyOperation = OperationTips.Instance(WaitStep, phone);
                    MyOperation.Show();
                }));

                if (currentStep.ExcuteState == "已执行")
                    return;
                if (this.CallInWaiting())
                {
                    PlayerSound((StepItemEnum)WaitStep.OperateId);
                    return;
                }
                EnvironmentContext.Logger.Info(currentStep.Id.ToString() + "," + currentStep.TaskId);
                CurStep = currentStep;
                WaitStep = currentStep;
                #region  替换关键字 Add by zzg
                ReplaceKeyword();
                #endregion 
                switch ((StepItemEnum)CurStep.OperateId)
                {
                    case StepItemEnum.无线电台_接听:
                        // PlayerSound((StepItemEnum)CurStep.OperateId);
                        this.Dispatcher.BeginInvoke(new Action(() =>
                        {
                            (this.LayoutPOC.Children[0] as WirelessTrainUC).Display();
                        }));
                        break;
                    case StepItemEnum.无线电台_呼入:
                        this.TextToSpeak(CurStep.StepContent, VoiceGender.Male);
                        AccountServiceProvider.Get_Instance().UpdateStepStatus(Login.examId, currentStep.Id);
                        break;
                    case StepItemEnum.无线电台_呼出:
                        this.Dispatcher.BeginInvoke(new Action(() =>
                        {
                            if (CurStep.Parameter == "First")
                            {
                                (this.LayoutPOC.Children[0] as WirelessTrainUC).waitTime.Add(CurStep.DeviceId);
                            }
                        }));
                        break;
                    case StepItemEnum.无线电台_响铃:
                        PlayerSound((StepItemEnum)CurStep.OperateId);
                        AccountServiceProvider.Get_Instance().UpdateStepStatus(Login.examId, CurStep.Id);
                        break;
                }
            }
        }

        /// <summary>
        /// 自由语音匹配
        /// </summary>
        private void ReplaceKeyword()
        {
            if ((StepItemEnum)CurStep.OperateId == StepItemEnum.无线电台_呼入
                || (StepItemEnum)CurStep.OperateId == StepItemEnum.调度电话_呼入)
            {
                List<string> temporarylist = new List<string>();
                temporarylist = ReciveIdentify;
                string talkContent = string.Join(",", ReciveIdentify.ToArray());

                var replayContet = CurStep.StepContent;
                Regex reg = new Regex(@"\{(\w+)\}");
                MatchCollection _MatchParaList = reg.Matches(replayContet);
                string temporary = string.Empty;
                foreach (var _Match in _MatchParaList)
                {
                    switch (_Match.ToString())
                    {
                        case "{时间}":
                            if (CurStep.Parameter == "非复述")
                            {
                                string _virtualTime = Convert.ToDateTime(VirtualTime).ToString("HH:mm");
                                CurStep.StepContent = CurStep.StepContent.Replace("{时间}", _virtualTime);
                            }
                            else
                            {
                                if (talkContent.Contains(":"))
                                {
                                    Regex time = new Regex(@"([01]?[0-9]|2[0-3]):[0-5][0-9]");
                                    MatchCollection _time = time.Matches(talkContent);
                                    if (_time.Count > 0)
                                    { CurStep.StepContent = CurStep.StepContent.Replace("{时间}", _time[0].ToString()); }

                                    else
                                    {
                                        CurStep.StepContent = CurStep.StepContent.Replace("命令时间{时间}", "");
                                    }
                                }
                                else if (talkContent.Contains("点"))
                                {
                                    var _endIndex = talkContent.IndexOf("点");
                                    if (_endIndex < 2)
                                        continue;
                                    var _orderNum = talkContent.Substring(_endIndex - 2, 2);
                                    Regex order = new Regex(@"(\d+)");
                                    MatchCollection _order = order.Matches(_orderNum);
                                    if (_order.Count > 0)
                                    {
                                        CurStep.StepContent = CurStep.StepContent.Replace("{时间}", _order[0].ToString() + "点");
                                    }
                                    else
                                        CurStep.StepContent = CurStep.StepContent.Replace("命令时间{时间}", "");
                                }
                                if (CurStep.StepContent.Contains("{时间}"))
                                {
                                    CurStep.StepContent = CurStep.StepContent.Replace("{时间}", "");
                                }
                            }
                            break;
                        case "{命令号}":
                            for (int i = 0; i < temporarylist.Count; i++)
                            {
                                if (temporarylist[i].Contains("命令"))
                                {
                                    if (temporarylist[i].Length > 2)
                                    {
                                        var _endIndex = temporarylist[i].IndexOf("号");
                                        if (_endIndex < 0)
                                            continue;
                                        var _orderNum = temporarylist[i].Substring(_endIndex - 2, 2);
                                        Regex order = new Regex(@"(\d+)");
                                        MatchCollection _order = order.Matches(_orderNum);
                                        if (_order.Count > 0)
                                        {
                                            CurStep.StepContent = CurStep.StepContent.Replace("{命令号}", _order[0].ToString());
                                            break;
                                        }
                                    }
                                }
                            }
                            if (CurStep.StepContent.Contains("{命令号}"))
                            {
                                CurStep.StepContent = CurStep.StepContent.Replace("命令{命令号}号", "");
                            }
                            break;
                        case "{调度员}":
                            if (talkContent.Contains("调度"))
                            {
                                string temporarystr = talkContent;
                                Regex rgx = new Regex("\\p{P}");
                                temporarystr = rgx.Replace(temporarystr, "");
                                Regex order = new Regex(@"调度员\s*\s*([\d\.]+)\s*(调度员)*");
                                MatchCollection _order = order.Matches(temporarystr);
                                if (_order.Count > 0)
                                    CurStep.StepContent = CurStep.StepContent.Replace("{调度员}", _order[0].ToString().Replace("调度员", ""));
                                else
                                {
                                    order = new Regex(@"调度\s*\s*([\d\.]+)\s*(调度)*");
                                    _order = order.Matches(temporarystr);
                                    if (_order.Count > 0)
                                        CurStep.StepContent = CurStep.StepContent.Replace("{调度员}", _order[0].ToString().Replace("调度", ""));
                                    else
                                    {
                                        CurStep.StepContent = CurStep.StepContent.Replace("调度员{调度员}", "");
                                    }
                                }
                            }
                            else
                            {
                                CurStep.StepContent = CurStep.StepContent.Replace("调度员{调度员}", "");
                            }
                            break;
                        case "{车组号}":
                            if (talkContent.Contains("受令处所"))
                            {
                                string temporarystr = talkContent;
                                Regex rgx = new Regex("\\p{P}");
                                temporarystr = rgx.Replace(temporarystr, "");
                                Regex order = new Regex(@"受令处所\s*\s*([\d\.]+)\s*(受令处所)*");
                                MatchCollection _order = order.Matches(temporarystr);
                                if (_order.Count > 0)
                                {
                                    if (_order[0].ToString().Length > 6)
                                    {
                                        CurStep.StepContent = CurStep.StepContent.Replace("{车组号}", _order[0].ToString().Replace("受令处所", "").Substring(0, 3));
                                    }
                                    else
                                    {
                                        CurStep.StepContent = CurStep.StepContent.Replace("受令处所{车组号}", "");
                                    }
                                }
                            }
                            else
                            {
                                CurStep.StepContent = CurStep.StepContent.Replace("受令处所{车组号}", "");
                            }
                            break;
                        case "{号表}":
                            for (int i = 0; i < temporarylist.Count; i++)
                            {
                                if (temporarylist[i].Contains("号表") && (temporarylist[i].Contains("t") || temporarylist[i].Contains("替")))
                                {
                                    if (temporarylist[i].Length > 2)
                                    {
                                        var _endIndex = temporarylist[i].IndexOf("号表");
                                        if (_endIndex == -1)
                                        {
                                            _endIndex = temporarylist[i].IndexOf("替表");
                                        }
                                        if (_endIndex < 0)
                                            continue;
                                        var _orderNum = temporarylist[i].Substring(_endIndex - 2);
                                        Regex order = new Regex(@"[\-\d\.]+");
                                        MatchCollection _order = order.Matches(_orderNum);
                                        if (_order.Count > 0)
                                        {
                                            CurStep.StepContent = CurStep.StepContent.Replace("{号表}", _order[0].ToString());
                                            temporarylist[i] = temporarylist[i].Replace(_order[0].ToString() + "号表", "");
                                            break;
                                        }
                                    }
                                }
                            }
                            if (CurStep.StepContent.Contains("{号表}"))
                            {
                                CurStep.StepContent = CurStep.StepContent.Replace("替{号表}号表", "");
                            }
                            break;
                        case "{车次号}":
                            for (int i = 0; i < temporarylist.Count; i++)
                            {
                                if (temporarylist[i].Contains("次列车"))
                                {
                                    if (temporarylist[i].Length > 7)
                                    {
                                        var _endIndex = temporarylist[i].IndexOf("次列车");
                                        if (_endIndex < 4)
                                            continue;
                                        var _orderNum = temporarylist[i].Substring(_endIndex - 4, 7);
                                        Regex order = new Regex(@"(\d+)");
                                        MatchCollection _order = order.Matches(_orderNum);
                                        //if (_order[0].ToString().Length == 5)
                                        //{

                                        //}
                                        if (_order.Count > 0 && _order[0].ToString().Length == 4)
                                        {
                                            CurStep.StepContent = CurStep.StepContent.Replace("{车次号}", _order[0].ToString() + "次列车");
                                            temporarylist[i] = temporarylist[i].Replace(_order[0].ToString() + "次列车", "");
                                            break;

                                        }
                                    }
                                }
                                else if (temporarylist[i].Contains("次"))
                                {
                                    if (temporarylist[i].Length > 5)
                                    {
                                        var _endIndex = temporarylist[i].IndexOf("次");
                                        if (_endIndex < 4)
                                            continue;
                                        var _orderNum = temporarylist[i].Substring(_endIndex - 4, 5);
                                        Regex order = new Regex(@"(\d+)");
                                        MatchCollection _order = order.Matches(_orderNum);
                                        if (_order.Count > 0 && _order[0].ToString().Length == 4)
                                        {
                                            CurStep.StepContent = CurStep.StepContent.Replace("{车次号}", _order[0].ToString() + "次");
                                            temporarylist[i] = temporarylist[i].Replace(_order[0].ToString() + "次", "");
                                            break;
                                        }
                                        break;
                                    }
                                }
                                else if (temporarylist[i].Contains("车"))
                                {
                                    if (temporarylist[i].Length > 5)
                                    {
                                        var _endIndex = temporarylist[i].IndexOf("车");
                                        if (_endIndex < 4)
                                            continue;
                                        var _orderNum = temporarylist[i].Substring(_endIndex - 4, 5);
                                        Regex order = new Regex(@"(\d+)");
                                        MatchCollection _order = order.Matches(_orderNum);
                                        if (_order.Count > 0 && _order[0].ToString().Length == 4)
                                        {
                                            CurStep.StepContent = CurStep.StepContent.Replace("{车次号}", _order[0].ToString() + "车");
                                            temporarylist[i] = temporarylist[i].Replace(_order[0].ToString() + "车", "");
                                            break;
                                        }
                                        break;
                                    }
                                }
                            }
                            if (CurStep.StepContent.Contains("{车次号}"))
                            {
                                CurStep.StepContent = CurStep.StepContent.Replace("{车次号}", "");
                            }
                            break;
                        case "{车次号1}":
                            for (int i = 0; i < temporarylist.Count; i++)
                            {
                                if (temporarylist[i].Contains("次列车"))
                                {
                                    if (temporarylist[i].Length > 7)
                                    {
                                        var _endIndex = temporarylist[i].IndexOf("次列车");
                                        if (_endIndex < 4)
                                            continue;
                                        var _orderNum = temporarylist[i].Substring(_endIndex - 4, 7);
                                        Regex order = new Regex(@"(\d+)");
                                        MatchCollection _order = order.Matches(_orderNum);
                                        if (_order.Count > 0 && _order[0].ToString().Length == 4)
                                        {
                                            CurStep.StepContent = CurStep.StepContent.Replace("{车次号1}", _order[0].ToString() + "次列车");
                                            temporarylist[i] = temporarylist[i].Replace(_order[0].ToString() + "次列车", "");
                                            break;
                                        }
                                        break;
                                    }
                                }
                                else if (temporarylist[i].Contains("次"))
                                {
                                    if (temporarylist[i].Length > 5)
                                    {
                                        var _endIndex = temporarylist[i].IndexOf("次");
                                        if (_endIndex < 4)
                                            continue;
                                        var _orderNum = temporarylist[i].Substring(_endIndex - 4, 5);
                                        Regex order = new Regex(@"(\d+)");
                                        MatchCollection _order = order.Matches(_orderNum);
                                        if (_order.Count > 0 && _order[0].ToString().Length == 4)
                                        {
                                            CurStep.StepContent = CurStep.StepContent.Replace("{车次号1}", _order[0].ToString() + "次");
                                            temporarylist[i] = temporarylist[i].Replace(_order[0].ToString() + "次", "");
                                            break;
                                        }
                                        break;
                                    }
                                }
                                else if (temporarylist[i].Contains("车"))
                                {
                                    if (temporarylist[i].Length > 5)
                                    {
                                        var _endIndex = temporarylist[i].IndexOf("车");
                                        if (_endIndex < 4)
                                            continue;
                                        var _orderNum = temporarylist[i].Substring(_endIndex - 4, 5);
                                        Regex order = new Regex(@"(\d+)");
                                        MatchCollection _order = order.Matches(_orderNum);
                                        if (_order.Count > 0 && _order[0].ToString().Length == 4)
                                        {
                                            CurStep.StepContent = CurStep.StepContent.Replace("{车次号}", _order[0].ToString() + "车");
                                            temporarylist[i] = temporarylist[i].Replace(_order[0].ToString() + "车", "");
                                            break;
                                        }
                                        break;
                                    }
                                }
                            }
                            if (CurStep.StepContent.Contains("{车次号1}"))
                            {
                                CurStep.StepContent = CurStep.StepContent.Replace("开{车次号1}", "");
                            }
                            break;
                        case "{方向}":
                            for (int i = 0; i < temporarylist.Count; i++)
                            {
                                if (temporarylist[i].Contains("上下行"))
                                {
                                    CurStep.StepContent = CurStep.StepContent.Replace("{方向}", "上下行");
                                }
                                else if (temporarylist[i].Contains("上行"))
                                {
                                    CurStep.StepContent = CurStep.StepContent.Replace("{方向}", "上行");
                                }
                                else if (temporarylist[i].Contains("下行"))
                                {
                                    CurStep.StepContent = CurStep.StepContent.Replace("{方向}", "下行");
                                }
                            }
                            break;
                    }
                }
            }
        }
        /// <summary>
        /// 打开直接输入语音文本
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SendControl_PreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            new SendCommand().Show();
        }
        /// <summary>
        /// 音频点击事件
        /// </summary>
        private void AudioControl_ThumbClick()
        {
            string message = string.Empty;
            ReciveIdentify.Clear();
            DynamicReception.Clear();
            OfflineSpeech.Instance().Show();
            if (this.AudioControl.PhoneState == POC.Controls.Enum.MicrophoneStateEnum.Closed)
            {
                this.AudioControl.PhoneState = POC.Controls.Enum.MicrophoneStateEnum.Opened;
                message = "Down";
            }
            else if (this.AudioControl.PhoneState == POC.Controls.Enum.MicrophoneStateEnum.Opened)
            {
                this.AudioControl.PhoneState = POC.Controls.Enum.MicrophoneStateEnum.Closed;
                message = "Up";
            }
            OfflineSpeech.Instance().SetTextBoxValue(message);
            offlineSpeechRecognitionclass.SendMessage(message);//给指定程序发送触发命令
        }
        /// <summary>
        /// 自由考核培训模式
        /// </summary>
        private void FreeExamModel()
        {
            while (true)
            {
                byte[] buffer = new byte[1000];
                _udpRecivesock.ReceiveFrom(buffer, ref point);//                            
                int index = 0;
                byte _frameHeader = buffer[0];
                index++;
                switch (_frameHeader)
                {
                    case 0xEB://教员注入故障后，将注入的故障进行播报。
                        var deviceType = buffer[index];//设备类型
                        index++;
                        switch (deviceType)
                        {
                            case 0x08:
                                var TrainID = BitConverter.ToInt16(buffer, index);//车组ID
                                index += 2;
                                var length1 = BitConverter.ToInt16(buffer, index);
                                index += 2;
                                string content1 = System.Text.Encoding.UTF8.GetString(buffer, index, length1);//需要播报的内容
                                PlayerSound(StepItemEnum.无线电台_呼入);
                                this.Dispatcher.Invoke(new Action(() =>
                                {
                                    var POCINFO = this.LayoutPOC.Children[0] as WirelessTrainUC;
                                    var callButton = POCINFO.TrainList.First(T => T.TrainGroupNumber == TrainID.ToString());
                                    if (callButton != null)
                                    {
                                        callButton.CallStatus = TetraCallStatus.CallInRinging;
                                        if (POCINFO.VoiceContent.ContainsKey((int)TrainID))
                                        {
                                            POCINFO.VoiceContent[(int)TrainID] = content1;
                                        }
                                        else
                                        {
                                            POCINFO.VoiceContent.Add((int)TrainID, content1);
                                        }
                                    }
                                }));
                                break;
                            case 0x0B:
                                var TrainID1 = BitConverter.ToInt16(buffer, index);//车组ID
                                index += 2;
                                var length2 = BitConverter.ToInt16(buffer, index);
                                index += 2;
                                string content2 = System.Text.Encoding.UTF8.GetString(buffer, index, length2);//需要播报的内容
                                PlayerSound(StepItemEnum.无线电台_呼入);
                                this.Dispatcher.Invoke(new Action(() =>
                                {
                                    var POCINFO = this.LayoutPOC.Children[0] as WirelessTrainUC;
                                    var callButton = POCINFO.TrainList.First(T => T.TrainGroupNumber == TrainID1.ToString());
                                    if (callButton != null)
                                    {
                                        callButton.CallStatus = TetraCallStatus.CallInRinging;
                                        if (POCINFO.VoiceContent.ContainsKey((int)TrainID1))
                                        {
                                            POCINFO.VoiceContent[(int)TrainID1] = content2;
                                        }
                                        else
                                        {
                                            POCINFO.VoiceContent.Add((int)TrainID1, content2);
                                        }
                                    }
                                }));
                                break;
                        }
                        break;
                    case 0xED://接收教员注入场景的车辆信息，(车组号|车次号|所属车站)
                        //取消此协议，改为考核模式获取虚拟时间
                        //var mainWindow=this.LayoutPOC.Children[0] as MainWindow;
                        //mainWindow.trinInfos= System.Text.Encoding.UTF8.GetString(buffer, index, buffer.Length);//获取车辆信息
                        break;
                    case 0xE2://当前系统的虚拟时间或真实时间---取消此协议，改为考核模式获取虚拟时间
                        //DateTime dateTime = new DateTime(BitConverter.ToInt64(buffer, index));
                        break;
                    case 0xab:
                        {
                            //index++;
                            if (buffer[index] == 0xba)
                            {
                                index++;
                                int length = buffer[index];
                                index++;
                                string text = Encoding.UTF8.GetString(buffer, index, length - index);
                                text = Encoding.UTF8.GetString(buffer, index, length);
                                text = Encoding.ASCII.GetString(buffer, index, length);
                                text = Encoding.Default.GetString(buffer, index, length);
                                this.TextToSpeak(text, VoiceGender.Female);
                            }
                        }
                        break;
                }
                System.Threading.Thread.Sleep(TimeSpan.FromMilliseconds(200));//200毫秒刷新一次
            }
        }

        /// <summary>
        /// 绑定Tetra的点击事件--Add by lukun
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private void TetraClick_Event(object sender, RoutedEventArgs args)
        {
            var source = (this.LayoutPOC.Children[0] as WirelessTrainUC).dgTrain.SelectedItem as TrainClass;
            if (source.CallStatus == TetraCallStatus.Talking)//当前为会话状态，播报语音内容
            {
                var _MainWindow = this.LayoutPOC.Children[0] as WirelessTrainUC;
                if (_MainWindow.VoiceContent.ContainsKey(Convert.ToInt32(source.TrainGroupNumber)))
                {
                    if (_MainWindow.VoiceContent[Convert.ToInt32(source.TrainGroupNumber)] != string.Empty)
                    {
                        this.TextToSpeak(_MainWindow.VoiceContent[Convert.ToInt32(source.TrainGroupNumber)], VoiceGender.Male);
                        _MainWindow.VoiceContent[Convert.ToInt32(source.TrainGroupNumber)] = string.Empty;
                    }
                }
            }
        }

        /// <summary>
        /// 发送消息到考核后台
        /// </summary>
        /// <param name="deviceID">设备ID</param>
        /// <param name="stepItemID">步骤ID</param>
        /// <param name="para">参数</param>
        /// <param name="deviceType">设备类型</param>
        private void SendDataToExam(short deviceID, int stepItemID, int para, int deviceType)
        {
            List<byte> data = new List<byte>();
            data.Add(0xEE);
            data.Add((byte)deviceType);//临时假的类型
            data.AddRange(BitConverter.GetBytes(deviceID));
            data.Add((byte)stepItemID);
            data.Add((byte)para);
            _udpSendSocket.SendTo(data.ToArray(), targetIpEndPoint); //发送数据
        }
        /// <summary>
        /// 结束等待咨询
        /// </summary>
        private void EndWaitInjectError()
        {
           // AccountServiceProvider.Get_Instance().SetMyWaitFlag();
        }

        /// <summary>
        /// 匹配语音库关键词
        /// </summary>
        private void MatchKeyWords()
        {
            this.Dispatcher.Invoke(new Action(() =>
            {
                REPLAY_CONTENT = string.Empty;
                VoiceLibraryModel voiceLibraryModel = new VoiceLibraryModel();
                Dictionary<string, string> ParaResults = new Dictionary<string, string>();
                var phone = (this.LayoutPOC.Children[0] as WirelessTrainUC).TrainList.ToList().FindAll(p => p.CallStatus == TetraCallStatus.Talking).FirstOrDefault();
                if (phone != null)
                {
                    if (CurSystemType == SystemType.ATS)
                    {
                        RSVoiceLibraryList = VoiceLibraryList.FindAll(T => T.DevType == 8);
                    }
                }
                else
                {
                    if (phone != null)
                    {
                        RSVoiceLibraryList = VoiceLibraryList.FindAll(T => T.DevType == 8);
                    }
                }
                for (int i = 0; i < DynamicReception.Count; i++)
                {
                    DynamicReception[i] = DynamicReception[i].Replace("t", "替");
                    DynamicReception[i] = DynamicReception[i].Replace("k", "开");
                    DynamicReception[i] = DynamicReception[i].Replace("零", "0");
                    DynamicReception[i] = DynamicReception[i].Replace("1列", "1联");
                    DynamicReception[i] = DynamicReception[i].Replace("1连", "1联");
                    DynamicReception[i] = DynamicReception[i].Replace("一列", "1联");
                    DynamicReception[i] = DynamicReception[i].Replace("一连", "1联");
                    DynamicReception[i] = DynamicReception[i].Replace("2列", "2联");
                    DynamicReception[i] = DynamicReception[i].Replace("2连", "2联");
                    DynamicReception[i] = DynamicReception[i].Replace("二列", "2联");
                    DynamicReception[i] = DynamicReception[i].Replace("二连", "2联");
                    DynamicReception[i] = DynamicReception[i].Replace("3列", "3联");
                    DynamicReception[i] = DynamicReception[i].Replace("3连", "3联");
                    DynamicReception[i] = DynamicReception[i].Replace("三列", "3联");
                    DynamicReception[i] = DynamicReception[i].Replace("三连", "3联");
                    DynamicReception[i] = DynamicReception[i].Replace("一", "1");
                    DynamicReception[i] = DynamicReception[i].Replace("二", "2");
                    DynamicReception[i] = DynamicReception[i].Replace("三", "3"); DynamicReception[i] = DynamicReception[i].Replace("四", "4"); DynamicReception[i] = DynamicReception[i].Replace("五", "5");
                    DynamicReception[i] = DynamicReception[i].Replace("六", "6"); DynamicReception[i] = DynamicReception[i].Replace("七", "7"); DynamicReception[i] = DynamicReception[i].Replace("期", "7");
                    DynamicReception[i] = DynamicReception[i].Replace("八", "8"); DynamicReception[i] = DynamicReception[i].Replace("九", "9"); DynamicReception[i] = DynamicReception[i].Replace("放倒", "放到");
                    DynamicReception[i] = DynamicReception[i].Replace("站治", "站至"); DynamicReception[i] = DynamicReception[i].Replace("站致", "站至"); DynamicReception[i] = DynamicReception[i].Replace("放置", "放至");
                    DynamicReception[i] = DynamicReception[i].Replace("4在", "次在"); DynamicReception[i] = DynamicReception[i].Replace("4再", "次在"); DynamicReception[i] = DynamicReception[i].Replace("占线", "站线"); DynamicReception[i] = DynamicReception[i].Replace("战线", "站线");
                    DynamicReception[i] = DynamicReception[i].Replace("次好", "次后"); DynamicReception[i] = DynamicReception[i].Replace("4号", "次后"); DynamicReception[i] = DynamicReception[i].Replace("4候", "次后");
                }
                string talkContent = string.Join(",", DynamicReception.ToArray());
                talkContent = talkContent.Replace("t", "替"); talkContent = talkContent.Replace("k", "开"); talkContent = talkContent.Replace("头", "端");//列车换端
                talkContent = talkContent.Replace("零", "0"); talkContent = talkContent.Replace("一", "1"); talkContent = talkContent.Replace("二", "2");
                talkContent = talkContent.Replace("三", "3"); talkContent = talkContent.Replace("四", "4"); talkContent = talkContent.Replace("五", "5");
                talkContent = talkContent.Replace("六", "6"); talkContent = talkContent.Replace("七", "7"); talkContent = talkContent.Replace("期", "7");
                talkContent = talkContent.Replace("八", "8"); talkContent = talkContent.Replace("九", "9");
                string TemptalkContent = talkContent;
                Dictionary<int, int> dicMatch = new Dictionary<int, int>();
                for (int i = 0; i < RSVoiceLibraryList.Count; i++)
                {
                    var VoiceModel = RSVoiceLibraryList[i];
                    if (VoiceModel.KeyWords == "")
                        continue;
                    var KeyWords = VoiceModel.KeyWords.Split('、').ToList();
                    var limitMatch = 0;
                    for (int j = 0; j < KeyWords.Count(); j++)
                    {
                        if (KeyWords[j].Contains("|"))
                        {
                            var _tempList = KeyWords[j].Split('|').ToList();
                            for (int p = 0; p < _tempList.Count(); p++)
                            {
                                if (talkContent.Contains(_tempList[p]))
                                {
                                    limitMatch++;
                                    break;
                                }
                            }
                        }
                        else
                        {
                            if (talkContent.Contains(KeyWords[j]))
                            {
                                limitMatch++;
                            }
                        }
                    }
                    if (limitMatch > 0)
                    {
                        if (VoiceModel.LimitMatch == limitMatch)
                        {
                            dicMatch.Add(VoiceModel.ID, limitMatch);
                            limitMatch = 0;
                        }
                    }
                }
                if (dicMatch.Count > 0)
                {
                    var _AllValus = dicMatch.Values.Max();
                    var Mykey = dicMatch.Where(T => T.Value == _AllValus).FirstOrDefault().Key;
                    var voiceMatch = RSVoiceLibraryList.Find(T => T.ID == Mykey);
                    if (voiceMatch.LimitMatch != _AllValus)
                        return;
                    voiceLibraryModel = voiceMatch;//找到匹配的语音库
                    var replayContet = voiceMatch.ReplyContent;
                    var Parameter = voiceMatch.Parameter;//命令参数
                    Regex reg = new Regex(@"\{(\w+)\}");
                    MatchCollection _MatchParaList = reg.Matches(Parameter);
                    foreach (var _Match in _MatchParaList)
                    {
                        switch (_Match.ToString())
                        {
                            case "{时间}":
                                if (talkContent.Contains(":"))
                                {
                                    Regex time = new Regex(@"([01]?[0-9]|2[0-3]):[0-5][0-9]");
                                    MatchCollection _time = time.Matches(talkContent);
                                    if (_time.Count > 0)
                                        replayContet = replayContet.Replace("{时间}", _time[0].ToString());
                                    else
                                        replayContet = replayContet.Replace("{时间}", "");
                                }
                                else if (talkContent.Contains("点"))
                                {
                                    var _endIndex = talkContent.IndexOf("点");
                                    if (_endIndex < 2)
                                        continue;
                                    var _orderNum = talkContent.Substring(_endIndex - 2, 2);
                                    Regex order = new Regex(@"(\d+)");
                                    MatchCollection _order = order.Matches(_orderNum);
                                    if (_order.Count > 0)
                                    {
                                        replayContet = replayContet.Replace("{时间}", _order[0].ToString() + "点");
                                    }
                                    else
                                        replayContet = replayContet.Replace("{时间}", "");
                                }
                                else
                                {
                                    replayContet = replayContet.Replace("{时间}", "");
                                }
                                break;
                            case "{命令号}":
                                if (talkContent.Contains("命令"))
                                {
                                    Regex order = new Regex(@"命令\s*\s*([\d\.]+)\s*(命令)*");
                                    MatchCollection _order = order.Matches(talkContent);
                                    if (_order.Count > 0)
                                        replayContet = replayContet.Replace("{命令号}", _order[0].ToString().Replace("命令", ""));
                                    else
                                    {
                                        if (talkContent.Contains("一号"))
                                        {
                                            replayContet = replayContet.Replace("{命令号}", "1");
                                        }
                                        else
                                        {
                                            replayContet = replayContet.Replace("命令{命令号}号", "");
                                        }
                                    }
                                }
                                else
                                {
                                    replayContet = replayContet.Replace("命令{命令号}号", "");
                                }
                                break;
                            case "{车组号}":
                                for (int i = 0; i < DynamicReception.Count; i++)
                                {
                                    if (DynamicReception[i].Length > 3)
                                    {
                                        int _endIndex = DynamicReception[i].IndexOf("车");
                                        if (_endIndex < 3)
                                            continue;
                                        var _orderNum = DynamicReception[i].Substring(_endIndex - 3, 4);
                                        Regex order = new Regex(@"(\d+)");
                                        MatchCollection _order = order.Matches(_orderNum);
                                        if (_order.Count > 0 && _order[0].ToString().Length == 3)
                                        {
                                            replayContet = replayContet.Replace("{车组号}", _order[0].ToString());
                                            DynamicReception[i] = DynamicReception[i].Replace(_order[0].ToString() + "车", "");
                                            ParaResults.Add("{车组号}", _order[0].ToString());
                                            break;
                                        }
                                        break;
                                    }
                                }
                                break;
                            case "{车次号}":
                                for (int i = 0; i < DynamicReception.Count; i++)
                                {
                                    if (DynamicReception[i].Contains("次列车"))
                                    {
                                        if (DynamicReception[i].Length > 7)
                                        {
                                            var _endIndex = DynamicReception[i].IndexOf("次列车");
                                            if (_endIndex < 4)
                                                continue;
                                            var _orderNum = DynamicReception[i].Substring(_endIndex - 4, 7);
                                            Regex order = new Regex(@"(\d+)");
                                            MatchCollection _order = order.Matches(_orderNum);
                                            if (_order.Count > 0 && _order[0].ToString().Length == 4)
                                            {
                                                replayContet = replayContet.Replace("{车次号}", _order[0].ToString());
                                                DynamicReception[i] = DynamicReception[i].Replace(_order[0].ToString() + "次列车", "");
                                                ParaResults.Add("{车次号}", _order[0].ToString());
                                                break;
                                            }
                                        }
                                    }
                                    else if (DynamicReception[i].Contains("次"))
                                    {
                                        if (DynamicReception[i].Length > 5)
                                        {
                                            var _endIndex = DynamicReception[i].IndexOf("次");
                                            if (_endIndex < 4)
                                                continue;
                                            var _orderNum = DynamicReception[i].Substring(_endIndex - 4, 5);
                                            Regex order = new Regex(@"(\d+)");
                                            MatchCollection _order = order.Matches(_orderNum);
                                            if (_order.Count > 0 && _order[0].ToString().Length == 4)
                                            {
                                                replayContet = replayContet.Replace("{车次号}", _order[0].ToString());
                                                DynamicReception[i] = DynamicReception[i].Replace(_order[0].ToString() + "次", "");
                                                ParaResults.Add("{车次号}", _order[0].ToString());
                                                break;
                                            }
                                            break;
                                        }
                                    }
                                    else if (DynamicReception[i].Contains("车"))
                                    {
                                        if (DynamicReception[i].Length > 5)
                                        {
                                            var _endIndex = DynamicReception[i].IndexOf("车");
                                            if (_endIndex < 4)
                                                continue;
                                            var _orderNum = DynamicReception[i].Substring(_endIndex - 4, 5);
                                            Regex order = new Regex(@"(\d+)");
                                            MatchCollection _order = order.Matches(_orderNum);
                                            if (_order.Count > 0 && _order[0].ToString().Length == 4)
                                            {
                                                replayContet = replayContet.Replace("{车次号}", _order[0].ToString());
                                                DynamicReception[i] = DynamicReception[i].Replace(_order[0].ToString() + "车", "");
                                                ParaResults.Add("{车次号}", _order[0].ToString());
                                                break;
                                            }
                                            break;
                                        }
                                    }
                                }
                                break;
                            case "{车次号1}":
                                for (int i = 0; i < DynamicReception.Count; i++)
                                {
                                    if (DynamicReception[i].Contains("次列车"))
                                    {
                                        if (DynamicReception[i].Length > 7)
                                        {
                                            var _endIndex = DynamicReception[i].IndexOf("次列车");
                                            if (_endIndex < 4)
                                                continue;
                                            var _orderNum = DynamicReception[i].Substring(_endIndex - 4, 7);
                                            Regex order = new Regex(@"(\d+)");
                                            MatchCollection _order = order.Matches(_orderNum);
                                            if (_order.Count > 0 && _order[0].ToString().Length == 4)
                                            {
                                                replayContet = replayContet.Replace("{车次号1}", _order[0].ToString());
                                                DynamicReception[i] = DynamicReception[i].Replace(_order[0].ToString() + "次列车", "");
                                                ParaResults.Add("{车次号1}", _order[0].ToString());
                                                break;
                                            }
                                            break;
                                        }
                                    }
                                    else if (DynamicReception[i].Contains("次"))
                                    {
                                        if (DynamicReception[i].Length > 5)
                                        {
                                            var _endIndex = DynamicReception[i].IndexOf("次");
                                            if (_endIndex < 4)
                                                continue;
                                            var _orderNum = DynamicReception[i].Substring(_endIndex - 4, 5);
                                            Regex order = new Regex(@"(\d+)");
                                            MatchCollection _order = order.Matches(_orderNum);
                                            if (_order.Count > 0 && _order[0].ToString().Length == 4)
                                            {
                                                replayContet = replayContet.Replace("{车次号1}", _order[0].ToString());
                                                DynamicReception[i] = DynamicReception[i].Replace(_order[0].ToString() + "次", "");
                                                ParaResults.Add("{车次号1}", _order[0].ToString());
                                                break;
                                            }
                                            break;
                                        }
                                    }
                                }
                                break;
                            case "{车次号2}":
                                for (int i = 0; i < DynamicReception.Count; i++)
                                {
                                    if (DynamicReception[i].Contains("次列车"))
                                    {
                                        if (DynamicReception[i].Length > 7)
                                        {
                                            var _endIndex = DynamicReception[i].IndexOf("次列车");
                                            if (_endIndex < 4)
                                                continue;
                                            var _orderNum = DynamicReception[i].Substring(_endIndex - 4, 7);
                                            Regex order = new Regex(@"(\d+)");
                                            MatchCollection _order = order.Matches(_orderNum);
                                            if (_order.Count > 0 && _order[0].ToString().Length == 4)
                                            {
                                                replayContet = replayContet.Replace("{车次号2}", _order[0].ToString());
                                                DynamicReception[i] = DynamicReception[i].Replace(_order[0].ToString() + "次列车", "");
                                                ParaResults.Add("{车次号2}", _order[0].ToString());
                                                break;
                                            }
                                            break;
                                        }
                                    }
                                    else if (DynamicReception[i].Contains("次"))
                                    {
                                        if (DynamicReception[i].Length > 5)
                                        {
                                            var _endIndex = DynamicReception[i].IndexOf("次");
                                            if (_endIndex < 4)
                                                continue;
                                            var _orderNum = DynamicReception[i].Substring(_endIndex - 4, 5);
                                            Regex order = new Regex(@"(\d+)");
                                            MatchCollection _order = order.Matches(_orderNum);
                                            if (_order.Count > 0 && _order[0].ToString().Length == 4)
                                            {
                                                replayContet = replayContet.Replace("{车次号2}", _order[0].ToString());
                                                DynamicReception[i] = DynamicReception[i].Replace(_order[0].ToString() + "次", "");
                                                ParaResults.Add("{车次号2}", _order[0].ToString());
                                                break;
                                            }
                                            break;
                                        }
                                    }
                                }
                                break;
                            case "{方向}":
                                if (talkContent.Contains("上行"))
                                {
                                    replayContet = replayContet.Replace("{方向}", "上行");
                                    ParaResults.Add("{方向}", "上行");
                                }
                                else if (talkContent.Contains("下行"))
                                {
                                    replayContet = replayContet.Replace("{方向}", "下行");
                                    ParaResults.Add("{方向}", "下行");
                                }
                                else
                                {
                                    replayContet = replayContet.Replace("{方向}", "");
                                }
                                break;
                            case "{联络线}":
                                for (int i = 0; i < DynamicReception.Count; i++)
                                {
                                    if (DynamicReception[i].Contains("联络线") || DynamicReception[i].Contains("转换轨"))
                                    {
                                        if (DynamicReception[i].Length >= 5)
                                        {
                                            var _endIndex = DynamicReception[i].IndexOf("号联络线");
                                            if (_endIndex == -1)
                                            {
                                                _endIndex = DynamicReception[i].IndexOf("号转换轨");
                                            }
                                            if (_endIndex == -1)
                                            {
                                                _endIndex = DynamicReception[i].IndexOf("连转换轨");
                                            }
                                            if (_endIndex == -1)
                                            {
                                                _endIndex = DynamicReception[i].IndexOf("联转换轨");
                                            }
                                            if (_endIndex < 0)
                                                continue;
                                            var _orderNum = DynamicReception[i].Substring(_endIndex - 1);
                                            Regex order = new Regex(@"(\d+)");
                                            MatchCollection _order = order.Matches(_orderNum);
                                            if (_order.Count > 0 && _order[0].ToString().Length == 1)
                                            {
                                                replayContet = replayContet.Replace("{联络线}", _order[0].ToString());
                                                DynamicReception[i] = DynamicReception[i].Replace(_order[0].ToString() + "号联络线", "");
                                                ParaResults.Add("{联络线}", _order[0].ToString());
                                                break;
                                            }
                                        }
                                    }
                                }
                                break;
                            case "{号表}":
                                for (int i = 0; i < DynamicReception.Count; i++)
                                {
                                    if (DynamicReception[i].Contains("号表"))
                                    {
                                        if (DynamicReception[i].Length > 2)
                                        {
                                            var _endIndex = DynamicReception[i].IndexOf("号表");
                                            if (_endIndex == -1)
                                            {
                                                _endIndex = DynamicReception[i].IndexOf("替表");
                                            }
                                            if (_endIndex < 0)
                                                continue;
                                            var _orderNum = DynamicReception[i].Substring(_endIndex - 2);
                                            Regex order = new Regex(@"[\-\d\.]+");
                                            MatchCollection _order = order.Matches(_orderNum);
                                            if (_order.Count > 0)
                                            {
                                                replayContet = replayContet.Replace("{号表}", _order[0].ToString());
                                                DynamicReception[i] = DynamicReception[i].Replace(_order[0].ToString() + "号表", "");
                                                ParaResults.Add("{号表}", _order[0].ToString());
                                                break;
                                            }
                                        }
                                    }
                                }
                                break;
                            case "{预备车}":
                                {
                                    var YBTrainList = (this.LayoutPOC.Children[0] as WirelessTrainUC).TrainList.ToList().FindAll(t => t.TrainGroupNumber.StartsWith("23")).ToList();
                                    if (YBTrainList.Count == 0)
                                    {
                                        replayContet = replayContet.Replace("{预备车}", "231");
                                        ParaResults.Add("{预备车}", "231");
                                        break;
                                    }
                                    else
                                    {
                                        var MaxNumber = YBTrainList.Max(t => Convert.ToInt32(t.TrainGroupNumber));
                                        MaxNumber += 1;
                                        string currentNumber = MaxNumber.ToString();
                                        replayContet = replayContet.Replace("{预备车}", currentNumber);
                                        ParaResults.Add("{预备车}", currentNumber);
                                        break;
                                    }
                                }
                        }
                    }
                    if (!replayContet.Contains("{"))
                    {
                        AnalysisATSOperation(voiceLibraryModel, ParaResults);
                        REPLAY_CONTENT = replayContet;
                        if (REPLAY_CONTENT.Contains("复诵"))
                        {
                            REPLAY_CONTENT = TemptalkContent;
                        }
                    }
                }
                dicMatch.Clear();
            }));
        }
        /// <summary>
        /// 识别到语音库中命令后，向ATS发送相应的步骤
        /// </summary>
        /// <param name="voiceLibraryModel">匹配到的语音库</param>
        /// <param name="voiceLibraryModel">语音库识别到的所有参数 {方向}、{车站}等</param>
        private void AnalysisATSOperation(VoiceLibraryModel voiceLibraryModel, Dictionary<string, string> ParaResults)
        {
            if (voiceLibraryModel.CommandStep == string.Empty || voiceLibraryModel.CommandStep == "NULL")
                return;
            //需要ATS系统执行的操作命令
            var CommandStep = voiceLibraryModel.CommandStep;
            var Parameter = voiceLibraryModel.Parameter;
            if (CommandStep.Contains('&'))
            {
                //取出需要ATS执行的多个操作，参数也需要隔开
                var CommandStepList = CommandStep.Split('&').ToList();
                var ParameterList = Parameter.Split('&').ToList();
                for (int i = 0; i < CommandStepList.Count; i++)
                {
                    SendToATSOpertionStep(CommandStepList[i], ParameterList[i], ParaResults);
                }
            }
            else
            {
                SendToATSOpertionStep(CommandStep, Parameter, ParaResults);
            }
        }
        /// <summary>
        /// 将来操作命令发送到ATS
        /// </summary>
        /// <param name="CommandStep">操作类型</param>
        /// <param name="aParas">参数</param>
        /// <param name="aParas">语音匹配解析到的参数</param>
        private void SendToATSOpertionStep(string CommandStep, string aParas, Dictionary<string, string> ParaResults)
        {
            try
            {
                if (aParas.Contains("、"))
                {
                    var _aParaList = aParas.Split('、').ToList();
                    foreach (var _para in _aParaList)
                    {
                        aParas = aParas.Replace(_para, ParaResults[_para]);
                    }
                }
                else
                {
                    aParas = aParas.Replace(aParas, ParaResults[aParas]);
                }
            }
            catch (Exception e)
            {

            }

            List<byte> data = new List<byte>();
            data.Add(0xC1);
            data.Add(0xC1);
            var _stepDatas = System.Text.Encoding.UTF8.GetBytes(CommandStep);
            data.AddRange(BitConverter.GetBytes(_stepDatas.Length));
            data.AddRange(_stepDatas);
            var _ParaDatas = System.Text.Encoding.UTF8.GetBytes(aParas);
            data.AddRange(BitConverter.GetBytes(_ParaDatas.Length));
            data.AddRange(_ParaDatas);
            _udpSendSocket.SendTo(data.ToArray(), data.Count, SocketFlags.None, targetIpEndPoint); //发送数据
            ////IPEndPoint targetIpEndPointAtsJY = new IPEndPoint(IPAddress.Parse("192.168.1.132"),Convert.ToInt32("20251"));
            //List<byte> dataToAts = new List<byte>();
            //dataToAts.Add(0xc1);
            //dataToAts.Add(0xc2);
            //var _stepDatasToAts = System.Text.Encoding.UTF8.GetBytes(CommandStep);
            //dataToAts.AddRange(BitConverter.GetBytes(_stepDatas.Length));
            //dataToAts.AddRange(_stepDatas);
            //var _ParaDatasToAts = System.Text.Encoding.UTF8.GetBytes(aParas);
            //dataToAts.AddRange(BitConverter.GetBytes(_ParaDatas.Length));
            //dataToAts.AddRange(_ParaDatas);
            //_udpSendSocket.SendTo(data.ToArray(), data.Count, SocketFlags.None, targetIpEndPoint); //发送数据
        }
        public void WinPosition()
        {
            #region 设置窗体大小及停靠位置
            //设置窗体宽度
            this.Width = SystemParameters.PrimaryScreenWidth * 0.5;
            //设置窗体高度   
            this.Height = SystemParameters.PrimaryScreenHeight * 1;
            this.Top = 0;
            this.Left = 0;
            #endregion
        }
        private Point pointToWindow;
        private void Configuring_Click(object sender, RoutedEventArgs e)
        {
            Point p = Mouse.GetPosition(e.Source as FrameworkElement);
            pointToWindow = (e.Source as FrameworkElement).PointToScreen(p);//转化为屏幕中的坐标
            ConfiguringWindow configuring = new ConfiguringWindow();
            configuring.Left = pointToWindow.X - 380;
            configuring.Top = pointToWindow.Y;
            configuring.WindowStartupLocation = WindowStartupLocation.Manual;
            configuring.Owner = this;
            configuring.ShowDialog();
        }
        List<CallRecordsModel> calls = new List<CallRecordsModel>();
        private void butRecord_Click(object sender, RoutedEventArgs e)
        {
            CallRecords callRecords = new CallRecords(calls);
            callRecords.ShowDialog();
        }
    }
    public class DataJson
    {
        public string State { get; set; }
        public string data { get; set; }
    }
}
